<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <!-- 搜索表单 -->
    <category-search
      @search="reload"
      :cache-key="getCurrentInstance().type.name"
    />
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
    >
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        flex-table
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :export-config="{ fileName: '商品分类数据', datasource: exportSource }"
        :print-config="{ datasource: exportSource }"
        cache-key="productCategory"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>

          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="action('remove')"
          >
            删除
          </el-button>
        </template>
        <template #cover="{ row }">
          <el-image
            :key="row.cover"
            fit="cover"
            :src="row.cover"
            :style="{
              maxWidth: '100%',
              height: '80px',
              cursor: 'zoom-in',
            }"
            @click="openPreview(index)"
          />
        </template>

        <template #type="{ row }">
          <el-tag
            v-if="row.type === 0"
            size="small"
            type="success"
            :disable-transitions="true"
          >
            首页
          </el-tag>
        </template>

        <template #status="{ row }">
          <el-switch
            size="small"
            :model-value="row.status === 1"
            @change="(checked) => editStatus(checked, row)"
          />
        </template>

        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            underline="never"
            @click="action('remove', row)"
          >
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>

    <ele-image-viewer
      v-model="showImageViewer"
      :urlList="viewerImages"
      :initialIndex="viewerIndex"
      :infinite="false"
      :hide-on-click-modal="true"
    />
    <!-- 新增 -->
    <category-edit action="add" v-model="showAdd" @done="reload" />

    <!-- 修改 -->
    <category-edit
      action="edit"
      :data="current"
      v-model="showEdit"
      @done="reload"
    />
  </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";

import { PlusOutlined, DeleteOutlined } from "@/components/icons";
import CategorySearch from "./components/category-search.vue";
import CategoryEdit from "./components/category-edit.vue";
import {
  pageCategorys,
  removeCategorys,
  listCategorys,
  updateCategoryStatus,
} from "@/api/product/category";
import { useOperator } from "@/hooks/operator";

import { useTable } from "@/hooks/useTable";
import { useModal } from "@/hooks/useModal";

defineOptions({ name: "SystemCategory" });

/** 是否打开图片预览 */
const showImageViewer = ref(false);

/** 图片预览数据 */
const viewerImages = ref([]);

/** 图片预览初始位置 */
const viewerIndex = ref(0);

/** 打开图片预览组件 */
const openPreview = (index) => {
  showImageViewer.value = true;
  viewerIndex.value = index;
};
/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "id",
    columnKey: "id",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "name",
    label: "商品名称",
    minWidth: 120,
  },
  {
    prop: "short_name",
    label: "商品简称",
    minWidth: 120,
  },

  {
    prop: "description",
    label: "服务描述",
    minWidth: 120,
  },

  {
    prop: "status",
    label: "状态",
    sortable: "custom",
    minWidth: 80,
    slot: "status",
  },
  {
    prop: "created_at",
    label: "创建时间",
    sortable: "custom",
    width: 180,
    align: "center",
  },
  {
    columnKey: "action",
    label: "操作",
    width: 120,
    align: "center",
    slot: "action",
    fixed: "right",
    hideInPrint: true,
    hideInExport: true,
  },
]);

/** 导出和打印全部数据的数据源 */
const exportSource = ({ where, orders }) => {
  return listCategorys({ ...where, ...orders });
};

const {
  loading,
  pagination,
  tableRef,
  datasource,
  reload,
  current,
  selections,
} = useTable({
  getPages: pageCategorys,
  beforeQuery: (params) => {
    // 可以修改或添加查询参数
    console.log("查询参数:", params); // 调试用，实际不需要这一行
    return {
      ...params,
      ...params.where,
    };
  },
});

/** 修改用户状态 */
const editStatus = (checked, row) => {
  console.log("editStatus", checked, row);
  const status = checked ? 1 : 0;
  action("status", row, {
    status: status,
    statusText: status ? "正常" : "冻结",
  });
};

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: async () => {
    current.value = null; // 新增时重置数据
    // if (!props.dict_ids) {
    //   throw new Error("请先选择字典");
    // }
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});

/** 删除 */
// 替换原有的remove方法
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      confirmText: "确定要删除{%s}这些数据吗?",
      api: removeCategorys,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
    status: {
      title: "状态",
      confirmText: "确定要切换为{%s}这些数据吗?",
      api: updateCategoryStatus,
      skipConfirm: true,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        // const status = checked ? 0 : 1;
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
  },
  selections,
  reload,
  idField: "id",
  idName: "title",
});
</script>
